package cz.hanis.android.geography.xml;

import java.io.IOException;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import cz.hanis.android.geography.models.Country;
import cz.hanis.android.geography.models.Test;


import android.content.Context;




public class XMLParser {

	public XMLParser() {		
	}
	
	private XMLReader initializeReader() throws ParserConfigurationException, SAXException {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser parser = factory.newSAXParser();
		XMLReader reader  = parser.getXMLReader();
		return reader;
	}
	
	
	public List<Country> parseCountries(Context context) {
		try {
			XMLReader xmlReader = initializeReader();			
			CountryHandler countryHandler = new CountryHandler();
			xmlReader.setContentHandler(countryHandler);
			InputSource inputSource = new InputSource(context.getAssets().open("countries.xml"));
			//InputSource inputSource = new InputSource (context.getResources().openRawResource(R.xml.flags));			
			inputSource.setEncoding("UTF-8");
			//XmlResourceParser parser = context.getResources().getXml(R.xml.countries);
			//parser.set
			xmlReader.parse(inputSource);
			return countryHandler.getCountryList();						
		} catch (ParserConfigurationException e) { 
			System.out.println("myerr:" + e.getMessage());
			e.printStackTrace();
		} catch (SAXException e) {
			System.out.println("myerr2:" + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("myerr3:" + e.getMessage());
			e.printStackTrace();
		}
		return null;					
	}
	
	
	public List<Test> parseTests(Context context) {
		try {
			XMLReader xmlReader = initializeReader();			
			TestHandler handler = new TestHandler();
			xmlReader.setContentHandler(handler);
			InputSource inputSource = new InputSource(context.getAssets().open("tests.xml"));
			inputSource.setEncoding("UTF-8");
			xmlReader.parse(inputSource);
			return handler.getTestList();					
		} catch (ParserConfigurationException e) { 
			System.out.println("myerr:" + e.getMessage());
			e.printStackTrace();
		} catch (SAXException e) {
			System.out.println("myerr2:" + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("myerr3:" + e.getMessage());
			e.printStackTrace();
		}
		return null;					
	}
		
	
}
 